<template>
  <div id="app">
    <div class="tech-bg"></div>

    <header class="app-header">
      <div class="header-left">
        <div class="logo-container">
          <div class="logo-icon">G</div>
          <span class="logo-text">Gim-Chat <span class="logo-suffix">PRO</span></span>
        </div>
      </div>
      
      <div class="header-right">
        <div class="user-info-panel">
          <template v-if="isLogin">
            <div class="avatar-wrapper">
              <img :src="userInfo.avatarUrl" alt="头像" class="user-avatar" />
              <div class="status-dot"></div>
            </div>
            <span class="username">{{ userInfo.userName }}</span>
            <el-button type="text" class="logout-btn" @click="doLogout">
              <i class="el-icon-switch-button"></i> 退出
            </el-button>
          </template>
          <template v-else>
            <el-button class="tech-btn primary" @click="doLogin" size="small">立即登录</el-button>
          </template>
        </div>
      </div>
    </header>

    <div class="app-body">
      <aside class="sidebar">
        <div class="nav-scroll">
          <ul class="nav-list">
            <li><router-link to="/chat" class="nav-item">
              <span class="icon">💬</span> <span class="text">智囊对话</span>
            </router-link></li>
            <li><router-link to="/group" class="nav-item">
              <span class="icon">🛠️</span> <span class="text">效能工具</span>
            </router-link></li>
            <li><router-link to="/docs" class="nav-item">
              <span class="icon">📄</span> <span class="text">文档中心</span>
            </router-link></li>
            <li><router-link to="/aiVideoCreate" class="nav-item">
              <span class="icon">🎬</span> <span class="text">AI 视频</span>
            </router-link></li>
            <li><router-link to="/newList" class="nav-item">
              <span class="icon">📰</span> <span class="text">前沿资讯</span>
            </router-link></li>
            <li><router-link to="/ai" class="nav-item ai-special">
              <img src="@/assets/images/avatar/openai.svg" class="nav-img-icon" /> 
              <span class="text">AI 核心</span>
            </router-link></li>
            <li><router-link to="/knowledge" class="nav-item">
              <span class="icon">📚</span> <span class="text">知识图谱</span>
            </router-link></li>
          </ul>
        </div>
        
        <div class="sidebar-footer">
           <router-link to="/setting" class="setting-link">
             <i class="el-icon-setting"></i> 系统设置
           </router-link>
        </div>
      </aside>

      <main class="main-view-container">
        <div class="main-view-content">
          <transition name="fade-transform" mode="out-in">
            <router-view />
          </transition>
        </div>
      </main>
    </div>

    <el-dialog 
      title="IDENTITY VERIFICATION" 
      :visible.sync="loginDialogVisible" 
      width="420px" 
      center 
      :show-close="true"
      :close-on-click-modal="false" 
      custom-class="tech-dialog">
      
      <div class="dialog-content-wrapper">
        <h2 class="login-title">用户登录</h2>
        <p class="login-subtitle">欢迎连接 Gim-Chat 智能终端</p>
        
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="tech-form">
          <el-form-item prop="phone">
            <el-input v-model="loginForm.phone" placeholder="请输入手机号" prefix-icon="el-icon-mobile-phone" class="tech-input"></el-input>
          </el-form-item>

          <el-form-item prop="passWord">
            <el-input v-model="loginForm.passWord" type="password" show-password placeholder="请输入密码" prefix-icon="el-icon-lock" class="tech-input"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitLogin" class="tech-btn block-btn">
              登 录 <i class="el-icon-right"></i>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import RightBar from '@/components/RightBar.vue'
import { handleLogin, handleLogout } from '@/api/user'
import WebSocketService from '@/plugins/ws';
import Vue from 'vue'

export default {
  components: { RightBar },
  data() {
    return {
      defaultAvatar: 'https://iknow-pic.cdn.bcebos.com/962bd40735fae6cd17bafbff1db30f2442a70f25',
      isRightbarCollapsed: true,
      loginDialogVisible: false,
      loginForm: {
        phone: "",
        passWord: "",
      },
      loginRules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入合法的手机号",
            trigger: "blur",
          },
        ],
        passWord: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  mounted() {
    window.addEventListener('beforeunload', this.clearLoginState);
  },
  beforeDestroy() {
    window.removeEventListener('beforeunload', this.clearLoginState);
  },
  computed: {
    isLogin() {
      return this.$store.getters['user/isLogin'];
    },
    userInfo() {
      return this.$store.state.user.userInfo || {}
    }
  },
  methods: {
    clearLoginState() {
      if (performance.getEntriesByType('navigation')[0].type !== 'reload') {
        this.$store.dispatch('user/logout');
      }
    },
    async submitLogin() {
      const that = this
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          const param = { ...this.loginForm }
          try {
            handleLogin(param).then(res => {
              const data = res.data.data;
              if (res.data.code === 200 && data.token) {
                const token = data.token;
                const user = data.userInfo;
                that.$store.dispatch('user/login', {
                  token,
                  userInfo: user
                });
                that.loginDialogVisible = false;
                that.$message.success('连接成功，欢迎回来');
                this.initWebSocket(user.userId)
              } else {
                that.$message.error(res.data.message || '登录失败');
              }
            })
          } catch (e) {
            console.error(e);
            that.$message.error('网络错误或服务异常');
          }
        }
      });
    },
    async doLogin() {
      this.loginDialogVisible = true;
    },
    async doLogout() {
      const param = {
        userId: this.userInfo.userId
      }
      const res = await handleLogout(param)
      if (res && res.data && res.data.code === 200) {
        this.$store.dispatch('user/logout')
        this.$message.success('已安全断开连接');
        this.$router.push({
          name: 'ai'
        });
      } else {
        this.$message.error(res.data.message);
      }
    },
    initWebSocket(userId) {
      if (this.wsService) {
        this.wsService.close();
      }
      this.wsService = new WebSocketService(this.$store);
      this.wsService.connect(userId);
      this.$ws = this.wsService; 
      Vue.prototype.$ws = this.wsService;
      this.$ws.send({})
    },
    clearCache() {
      this.$store.dispatch('user/logout');
    }
  },
};
</script>

<style lang="less" scoped>
/* ================= 变量定义 ================= */
@bg-dark: #0f1219;
@bg-panel: #1a1f2c;
@primary-color: #00f2ff; /* 赛博青色 */
@accent-color: #7d2ae8; /* 霓虹紫 */
@text-main: #e2e8f0;
@text-sub: #94a3b8;
@glass-bg: rgba(20, 25, 40, 0.75);
@border-color: rgba(255, 255, 255, 0.08);

/* ================= 全局布局 ================= */
#app {
  height: 100vh;
  display: flex;
  flex-direction: column;
  font-family: 'Inter', 'Helvetica Neue', Arial, sans-serif;
  background-color: @bg-dark;
  color: @text-main;
  overflow: hidden;
  position: relative;
}

/* 背景纹理 */
.tech-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  background: 
    radial-gradient(circle at 15% 50%, rgba(125, 42, 232, 0.08) 0%, transparent 25%),
    radial-gradient(circle at 85% 30%, rgba(0, 242, 255, 0.05) 0%, transparent 25%);
  pointer-events: none;
}

/* ================= 顶部导航栏 ================= */
.app-header {
  height: 64px;
  background: @glass-bg;
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border-bottom: 1px solid @border-color;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  z-index: 100;
  box-shadow: 0 4px 20px rgba(0,0,0,0.2);

  .logo-container {
    display: flex;
    align-items: center;
    cursor: pointer;
    
    .logo-icon {
      width: 32px;
      height: 32px;
      background: linear-gradient(135deg, @primary-color, @accent-color);
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 900;
      color: #fff;
      margin-right: 12px;
      box-shadow: 0 0 10px rgba(0, 242, 255, 0.3);
    }

    .logo-text {
      font-size: 20px;
      font-weight: 700;
      letter-spacing: 0.5px;
      color: #fff;
      
      .logo-suffix {
        font-size: 10px;
        background: rgba(255,255,255,0.1);
        padding: 2px 6px;
        border-radius: 4px;
        margin-left: 4px;
        color: @primary-color;
      }
    }
  }

  .user-info-panel {
    display: flex;
    align-items: center;
    gap: 16px;

    .avatar-wrapper {
      position: relative;
      .user-avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        border: 2px solid rgba(255,255,255,0.1);
        transition: all 0.3s;
        &:hover {
          border-color: @primary-color;
        }
      }
      .status-dot {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 10px;
        height: 10px;
        background: #10b981;
        border: 2px solid @bg-panel;
        border-radius: 50%;
      }
    }

    .username {
      font-size: 14px;
      font-weight: 500;
    }

    .logout-btn {
      color: @text-sub;
      &:hover {
        color: #ff4d4f;
      }
    }
  }
}

/* ================= 主体布局 ================= */
.app-body {
  flex: 1;
  display: flex;
  overflow: hidden;
  z-index: 10;
}

/* ================= 左侧侧边栏 ================= */
.sidebar {
  width: 220px;
  background: rgba(18, 22, 33, 0.6);
  backdrop-filter: blur(10px);
  border-right: 1px solid @border-color;
  display: flex;
  flex-direction: column;
  padding: 20px 12px;
  transition: all 0.3s ease;

  .nav-scroll {
    flex: 1;
    overflow-y: auto;
    &::-webkit-scrollbar { width: 0; }
  }

  .nav-list {
    list-style: none;
    padding: 0;
    margin: 0;

    li {
      margin-bottom: 8px;
    }

    .nav-item {
      display: flex;
      align-items: center;
      padding: 12px 16px;
      color: @text-sub;
      text-decoration: none;
      border-radius: 12px;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      font-size: 15px;
      position: relative;
      overflow: hidden;

      .icon { margin-right: 12px; font-size: 18px; filter: grayscale(100%); transition: 0.3s; }
      .nav-img-icon { width: 20px; height: 20px; margin-right: 12px; filter: grayscale(100%); transition: 0.3s; }
      
      /* 悬停效果 */
      &:hover {
        background: rgba(255, 255, 255, 0.03);
        color: @text-main;
        .icon, .nav-img-icon { filter: grayscale(0); transform: scale(1.1); }
      }

      /* 激活状态 */
      &.router-link-active {
        background: linear-gradient(90deg, rgba(0, 242, 255, 0.1) 0%, transparent 100%);
        color: @primary-color;
        font-weight: 600;
        
        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 15%;
          bottom: 15%;
          width: 3px;
          background: @primary-color;
          border-radius: 0 4px 4px 0;
          box-shadow: 0 0 8px @primary-color;
        }

        .icon, .nav-img-icon { filter: grayscale(0); }
      }

      /* AI 特殊菜单 */
      &.ai-special {
        &.router-link-active {
          color: @accent-color;
          &::before { background: @accent-color; box-shadow: 0 0 8px @accent-color; }
          background: linear-gradient(90deg, rgba(125, 42, 232, 0.1) 0%, transparent 100%);
        }
      }
    }
  }

  .sidebar-footer {
    padding-top: 20px;
    border-top: 1px solid @border-color;
    
    .setting-link {
      display: flex;
      align-items: center;
      justify-content: center;
      color: @text-sub;
      text-decoration: none;
      font-size: 14px;
      padding: 10px;
      border-radius: 8px;
      transition: 0.3s;
      &:hover {
        background: rgba(255,255,255,0.05);
        color: @text-main;
      }
      i { margin-right: 6px; }
    }
  }
}

/* ================= 主内容容器 ================= */
.main-view-container {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  position: relative;
}

.main-view-content {
  width: 100%;
  height: 100%;
  background: rgba(30, 34, 45, 0.5); /* 半透明内容背景 */
  border-radius: 16px;
  border: 1px solid @border-color;
  box-shadow: inset 0 0 20px rgba(0,0,0,0.2);
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;

  /* 自定义滚动条 */
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-track {
    background: transparent;
  }
  &::-webkit-scrollbar-thumb {
    background: rgba(255,255,255,0.1);
    border-radius: 3px;
    &:hover { background: rgba(255,255,255,0.2); }
  }
}

/* ================= 动画 ================= */
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}
.fade-transform-enter {
  opacity: 0;
  transform: translateY(10px);
}
.fade-transform-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

/* ================= Element UI 深度覆盖 (Dark Mode) ================= */
/* 按钮样式 */
.tech-btn {
  &.primary {
    background: linear-gradient(135deg, #006eff, #00f2ff);
    border: none;
    box-shadow: 0 4px 15px rgba(0, 242, 255, 0.3);
    font-weight: 600;
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 6px 20px rgba(0, 242, 255, 0.5);
    }
  }
  &.block-btn {
    width: 100%;
    height: 42px;
    font-size: 16px;
    letter-spacing: 2px;
  }
}

/* 弹窗样式覆盖 */
::v-deep .tech-dialog {
  background: #1a1d26;
  border: 1px solid rgba(0, 242, 255, 0.2);
  box-shadow: 0 0 40px rgba(0, 0, 0, 0.6);
  border-radius: 12px;

  .el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid rgba(255,255,255,0.05);
    .el-dialog__title {
      color: @primary-color;
      font-size: 14px;
      letter-spacing: 1px;
      font-family: monospace;
    }
    .el-dialog__close { color: @text-sub; &:hover { color: #fff; } }
  }

  .el-dialog__body {
    padding: 30px;
    color: @text-main;
  }
}

/* 登录表单内部 */
.dialog-content-wrapper {
  text-align: center;
  
  .login-title {
    font-size: 24px;
    color: #fff;
    margin-bottom: 8px;
    font-weight: 600;
  }
  .login-subtitle {
    color: @text-sub;
    font-size: 13px;
    margin-bottom: 30px;
  }
}

::v-deep .tech-form {
  .el-form-item__label {
    color: @text-sub;
  }
  
  /* 输入框样式覆盖 */
  .el-input__inner {
    background: rgba(0,0,0,0.2);
    border: 1px solid rgba(255,255,255,0.1);
    color: #fff;
    height: 44px;
    border-radius: 8px;
    &:focus {
      border-color: @primary-color;
      box-shadow: 0 0 0 2px rgba(0, 242, 255, 0.1);
    }
  }
  
  .el-input__icon {
    color: @text-sub;
  }
}

</style>